package com.cw.japp

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.name.Rename;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import grails.plugin.springsecurity.annotation.Secured;

import java.text.DateFormat;
import java.text.SimpleDateFormat

class LandingController {
	def springSecurityService
	
	def messageSource // inject the messageSource
	
	def index() {
		if(springSecurityService.isLoggedIn()){
			redirect(controller:'home',action:'index',params:params)
		}else{
			redirect(action: "show", params: params)
		}
	}

	
    def show() { 
		def role = Role.findByAuthority("ROLE_MODEL")
		def models = UserRole.findAllByRole(role).user
		[models:models]
	}
	
	
	def modelSignUp() { 
		flash.clear();
		[isSignUp : "modelSignUp"]
	 }
	
	
	def support() {
		if(springSecurityService.isLoggedIn()){
			def userDetails = springSecurityService.principal
			def user = User.get(userDetails.id);
			[userInstance: user]
		}
	}
	
	def termsConditions() {
		if(springSecurityService.isLoggedIn()){
			def userDetails = springSecurityService.principal
			def user = User.get(userDetails.id);
			[userInstance: user]
		}
	}
	
	def privacyPolicy() {
		if(springSecurityService.isLoggedIn()){
			def userDetails = springSecurityService.principal
			def user = User.get(userDetails.id);
			[userInstance: user]
		}
	}
	
	def help() {
		if(springSecurityService.isLoggedIn()){
			def userDetails = springSecurityService.principal
			def user = User.get(userDetails.id);
			[userInstance: user]
		}
	}
	
	def modelSignUpProcess()
	{
		def isError = false;
		flash.clear();
		
		if(params.password != params.confirmPassword)
		{
			flash.passwordDoesNotMatch = "Password and Confirm Password does not match.";
			isError = true;
		}
		if(params.email != params.confirmEmail)
		{
			flash.confirmEmailDoesNotMatch = "Email and Confirm Email does not match.";
			isError = true;
		}
		if(params.dob_year.isEmpty() || params.dob_day.isEmpty() || params.dob_month.isEmpty())
		{
			flash.dobEmpty = "Please provide your date of birth.";
			isError = true;
		}
		
		String query = "select count(*) from User where username= ?";
		def sot = User.executeQuery(query, params.username);
		
	   if (sot && sot.get(0) > 0){
		  flash.userAlreadyExists = "Username already exists. Please provide some other username.";
		  isError = true;
	   }
	   
	   if(!validatePassword(params.password))
	   {
		   flash.passwordDoesNotMatch = "Password should be 6 characters long and must contain atleast one number, one alphabet and one special character";
		   isError = true;
	   }
	  
	   chkIfCorrectImageUploaded();
	   
		if(isError)
		{
			render(view: 'modelSignUp',model : [username : params.username, firstName:params.firstName, lastName : params.lastName, email: params.email, confirmEmail: params.confirmEmail, description : params.description, userType : params.userType, pictureUri : params.pictureUri, isSignUp : params.isSignUp]);
			return;
		}
		
		
		def user = new User(username : params.username, password : params.password, email: params.email, description : params.description, firstName:params.firstName, lastName : params.lastName, birthDate : params.dob, createdDate: new Date(), lastModifiedDate: new Date(), status: 1);//new Date(params.dob_year, params.dob_month, params.dob_day)
		//pictureUri : file.getAbsolutePath()+"/"+reportDate+name
		def info = user.save();

		if (user.errors && user.errors.errorCount > 0) {
			//log.warn myDomainObj.errors.allErrors.join(' \n') //each error is an instance of  org.springframework.validation.FieldError
/*			if(user.errors.allErrors.join(' \n').contains("email"))
			{*/
				user.errors.allErrors.each {flash.isErrors = "Validation errors : "+ messageSource.getMessage(it, null)}
				//flash.isErrors = "Validation errors : Email is not valid. Please provide a valid email address." ;
				render(view: 'modelSignUp',model : [username : params.username, firstName:params.firstName, lastName : params.lastName, email: params.email, confirmEmail: params.confirmEmail, description : params.description, userType : params.userType, pictureUri : params.pictureUri, isSignUp : params.isSignUp]);
				return;
			//}
		 }
		if(info)
		{
			if(params.isSignUp.equals("modelSignUp"))
			{
				def modelRole = Role.findByAuthorityIlike("ROLE_MODEL")
				UserRole.create user, modelRole, true
			}
			def userRole = Role.findByAuthorityIlike("ROLE_USER")
			UserRole.create user, userRole, true
			//def users = new Users(login : params.username, password : params.password, email: params.email, description : params.description, firstName:params.firstName, lastName : params.lastName, age : params.date('dob', 'dd-MM-yyyy'), userType : params.userType, pictureUri : params.pictureUri);
			
			uploadImage(info.id);
			
			//users.save();
			springSecurityService.reauthenticate(params.username, params.password)
			redirect(controller : 'home')
		}
	}
	
	def chkIfCorrectImageUploaded()
	{
		String s=""
		CommonsMultipartFile f=request.getFile('pictureUri')
		String name = f.getOriginalFilename()
		if(name)
		{
			String mimeType = f.getContentType();
			if (mimeType == null || !mimeType.startsWith("image")) {
				flash.invalidImageUploaded = "Invalid image uploaded. Please insure that uploaded image has standard extension.";
				render(view: 'modelSignUp',model : [username : params.username, firstName:params.firstName, lastName : params.lastName, email: params.email, confirmEmail: params.confirmEmail, description : params.description, userType : params.userType, pictureUri : params.pictureUri]);
				return;
			}
		}
	}
	
	def uploadImage(Long userId)
	{
		def user = User.get(userId)
		CommonsMultipartFile f=request.getFile('pictureUri')
		String name = f.getOriginalFilename()
		if(name)
		{
			File file = new File(request.getSession().getServletContext().getRealPath("/")+"../profileImages/"+userId+"/");
			file.mkdirs();
			DateFormat df = new SimpleDateFormat("MMddyyyyHHmmss");
			String reportDate = df.format(new Date());
			String fileName = file.getAbsolutePath()+"/"+name.substring(0, name.lastIndexOf("."))+ "_" +reportDate
			def fos= new FileOutputStream(fileName+name.substring(name.lastIndexOf(".")));
			f.getBytes().each{ fos.write(it) }
			fos.flush()
			fos.close()
			
			Thumbnails.of(f.getInputStream())
			.size(420, 320)
			.outputFormat("jpg")
			.toFile(fileName + "_thumbnail.jpg");
			
			user.setPictureUri(fileName + name.substring(name.lastIndexOf(".")))
			//def user1 = new User(pictureUri : file.getAbsolutePath()+"/"+reportDate+name);
			user.save();
		}
	}
	
	def signUp() {
		
		flash.clear();
		render(view : 'modelSignUp', model : [isSignUp : "userSignUp"]);
	}
	
	def profileImageUpload() {
		String profilePicturePath = params.pictureUri;
		if(profilePicturePath)
		{
			try{
				
				File file = new File(profilePicturePath.substring(0, profilePicturePath.lastIndexOf(".")) + "_thumbnail.jpg")
				response.contentType = URLConnection.guessContentTypeFromName(file.getName())
				response.outputStream << file.bytes
				response.outputStream.flush()
			}catch(Exception e ){
				
				//Need to implement logger to log exceptions
			}
		}
	}
	
	boolean validatePassword(String pass) {
		return (pass) && (pass.length() > 5) && (pass =~ /\p{Alpha}/) &&
			   (pass =~ /\p{Digit}/) && (pass =~ /[!@#$%*&+()]/)
	  }
}
